package org.geektimes.include;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.configuration.microprofile.config.source.servlet.ServletContextConfigSource;
import org.geektimes.injection.component.ComponentBean;
import org.geektimes.injection.context.ComponentContext;
import org.geektimes.injection.context.Initializer.IncludeComponentInitializer;

import javax.servlet.ServletContext;

/**
 * @FileName: MicroprofileComponentInitializer
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2021/3/18 - 17:41
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class MicroprofileComponentInitializer implements IncludeComponentInitializer {
    /**
     * 初始化方法,将第三方组件注册到容器上下文对象中
     *
     * @param componentContext
     */
    @Override
    public void init(ComponentContext componentContext) {
        // ConfigProviderResolver configProviderResolver = new DefaultConfigProviderResolver();
        // Config config = configProviderResolver.getConfig();
        // componentContext.putComponent(Config.class.getSimpleName(), new ComponentBean(config));

        ServletContext servletContext = componentContext.getServletContext();
        ServletContextConfigSource servletContextConfigSource = new ServletContextConfigSource(servletContext);
        // 获取当前 ClassLoader
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
        ConfigBuilder configBuilder = configProviderResolver.getBuilder();
        // 配置 ClassLoader
        configBuilder.forClassLoader(classLoader);
        // 默认配置源（内建的，静态的）
        configBuilder.addDefaultSources();
        // 通过发现配置源（动态的）
        configBuilder.addDiscoveredConverters();
        // 增加扩展配置源（基于 Servlet 引擎）
        configBuilder.withSources(servletContextConfigSource);
        // 获取 Config
        Config config = configBuilder.build();
        // 注册 Config 关联到当前 ClassLoader
        configProviderResolver.registerConfig(config, classLoader);

        // 将Config对象交给ComponentContext容器管理
        componentContext.putComponent(Config.class.getSimpleName(), new ComponentBean(config));
    }

    /**
     * 组件 销毁方法
     *
     * @param componentContext
     */
    @Override
    public void destroy(ComponentContext componentContext) {

    }
}
